//
//  AnswerScrollView.m
//  答题控件
//
//  Created by dcr on 2017/1/10.
//  Copyright © 2017年 邓兆太. All rights reserved.
//

#import "AnswerScrollView.h"
#import "AnswerTableViewCell.h"
#import "AnswerModel.h"
#import "CommonUtils.h"
#import "QuestionCollectManager.h"
#define SIZE self.frame.size

@interface AnswerScrollView()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@end
@implementation AnswerScrollView
{
    UITableView *_leftTableView;
    UITableView *_mainTableView;
    UITableView *_rightTableView;
}

- (instancetype)initWithFrame:(CGRect)frame andDataArray:(NSArray *)array{
    self = [super initWithFrame:frame];
    if(self){
        _currentPage = 0;
        _datas = [[NSArray alloc]initWithArray:array];
        _hadAnswerArray = [[NSMutableArray alloc]init];
        for(int i = 0; i < _datas.count; i++){
            [_hadAnswerArray addObject:@"0"];
        }
        _scrollView = [[UIScrollView alloc]initWithFrame:frame];
        _scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = true;
        _scrollView.bounces = false;
        _leftTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _mainTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        _rightTableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStyleGrouped];
        
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.scrollEnabled = false;
        
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.scrollEnabled = false;
        
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.scrollEnabled = false;
        
        if(_datas.count >= 3){
            _scrollView.contentSize = CGSizeMake(3*SIZE.width, SIZE.height);
        }else{
            _scrollView.contentSize = CGSizeMake(_datas.count*SIZE.width, SIZE.height);
        }
        [self createView];
    }
    return self;
}

- (void)createView{
    _leftTableView.frame = CGRectMake(0, 0, SIZE.width, SIZE.height);
    _mainTableView.frame = CGRectMake(SIZE.width, 0, SIZE.width, SIZE.height);
    _rightTableView.frame = CGRectMake(SIZE.width*2, 0, SIZE.width, SIZE.height);
    [_scrollView addSubview:_leftTableView];
    [_scrollView addSubview:_mainTableView];
    [_scrollView addSubview:_rightTableView];
    [self addSubview:_scrollView];
}

//显示行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    AnswerModel *model = [self getTheFitModel:tableView];
    if([model.mtype intValue] == 1){
        return 4;
    }else{
        return 2;
    }
}

//脚的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = [self getFooterHeight:tableView];
    return height > 80 ? height : 80;
}

- (CGFloat)getFooterHeight:(UITableView *)tableView{
    NSString *str = [self getFooterString:tableView];
    UIFont *font = [UIFont systemFontOfSize:16];
    return [CommonUtils getSizeWithString:str withFont:font withWidth:tableView.frame.size.width].height+40;
}

- (NSString *)getFooterString:(UITableView *)tableView{
    AnswerModel *model = [self getTheFitModel:tableView];
    return [NSString stringWithFormat:@"答案解析：%@", model.mdesc];
}

//头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    NSString *str = [self getHeaderString:tableView];
    UIFont *font = [UIFont systemFontOfSize:16];
    CGFloat height = [CommonUtils getSizeWithString:str withFont:font withWidth:tableView.frame.size.width].height+30;
    AnswerModel *model = [self getTheFitModel:tableView];
    if(![model.mimage isEqualToString:@""]){
        UIImage *image = [UIImage imageNamed:model.mid];
        height += image.size.height;
    }
    return height > 80 ? height : 80;
}

//头的View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
    NSString *str = [self getHeaderString:tableView];
    UIFont *font = [UIFont systemFontOfSize:16];
    CGFloat labelHeight = [CommonUtils getSizeWithString:str withFont:font withWidth:tableView.frame.size.width].height;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZE.width, height)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, tableView.frame.size.width-20, labelHeight+30)];
    int index = [self getQuestionNumber:tableView andCurPage:_currentPage];
    label.text = [NSString stringWithFormat:@"%d.%@", index+1, str];
    [label setFont:font];
    label.numberOfLines = 0;
    [view addSubview:label];
    AnswerModel *model = [self getTheFitModel:tableView];
    if(![model.mimage isEqualToString:@""]){
        UIImage *image = [UIImage imageNamed:model.mid];
        height += image.size.height;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(tableView.frame.size.width/2-image.size.width/2, label.frame.origin.y+label.frame.size.height-10, image.size.width, image.size.height)];
        [imageView setImage:image];
        [view addSubview:imageView];
    }
    return view;
}

- (NSString *)getHeaderString:(UITableView *)tableView{
    AnswerModel *model = [self getTheFitModel:tableView];
    if([model.mtype intValue] == 1){
        return [[CommonUtils getAnswerWithString:model.mquestion] objectAtIndex:0];
    }else{
        return model.mquestion;
    }
}

- (int)getQuestionNumber:(UITableView *)tableView andCurPage:(int)page{
    if(_datas.count >= 3){
        if(_leftTableView == tableView && page == 0){
            return 0;
        }else if(_leftTableView == tableView && page > 0){
            return page-1;
        }else if(_mainTableView == tableView && page == 0){
            return 1;
        }else if(_mainTableView == tableView && page > 0 && page < _datas.count-1){
            return page;
        }else if(_mainTableView == tableView && page == _datas.count-1){
            return page-1;
        }else if(_rightTableView == tableView && page == 0){
            return 2;
        }else if(_rightTableView == tableView && page < _datas.count-1){
            return page+1;
        }else if(_rightTableView == tableView && page == _datas.count-1){
            return page;
        }
        return 0;
    }
    return page;
}

//脚View
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = [self getFooterHeight:tableView];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZE.width, height)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, tableView.frame.size.width-20, height-20)];
    label.text = [self getFooterString:tableView];
    [label setFont:[UIFont systemFontOfSize:16]];
    label.numberOfLines = 0;
    [view addSubview:label];
    int page = [self getQuestionNumber:tableView andCurPage:_currentPage];
    if([_hadAnswerArray[page] intValue] == 0){
        return nil;
    }
    return view;
}

//返回Cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = [self getCellHeight:tableView cellForRowAtIndexPath:indexPath];
    return height > 44 ? height : 44;
}

- (CGFloat)getCellHeight:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [self getCellString:tableView cellForRowAtIndexPath:indexPath];
    
    CGFloat height = [CommonUtils getSizeWithString:str withFont:WeekFont3 withWidth:220].height+20;
    return height;
}

- (NSString *)getCellString:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AnswerModel *model = [self getTheFitModel:tableView];
    if([model.mtype intValue] == 1){
        return [[CommonUtils getAnswerWithString:model.mquestion] objectAtIndex:indexPath.row+1];
    }else{
        return model.manswer;
    }
}

//点击每个Item时调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    int page = [self getQuestionNumber:tableView andCurPage:_currentPage];
    if([_hadAnswerArray[page] intValue] != 0){
        return;
    }
    AnswerModel *model = [self getTheFitModel:tableView];
    //1为选择题2为判断题
    if([model.mtype intValue] == 1){
        //错题存档
        if(![model.manswer isEqualToString:[NSString stringWithFormat:@"%c", (char)('A'+indexPath.row)]]){
            [QuestionCollectManager addWrongQuestion:[model.mid intValue]];
        }
    }else{
        //判断题错题存档
        AnswerTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if(![model.manswer isEqualToString:cell.answerLabel.text]){
            [QuestionCollectManager addWrongQuestion:[model.mid intValue]];
        }
    }
    //保存已做过的题，在优先未做题中要用到
    [QuestionCollectManager addDoneQuestion:[model.mid intValue]];
    [_hadAnswerArray replaceObjectAtIndex:page withObject:[NSString stringWithFormat:@"%d", (int)(indexPath.row+1)]];
    [self reloadData];
}

//绘制每个Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AnswerTableViewCell *cell = [AnswerTableViewCell cellWithTableView:tableView];
    //设置圆角
    cell.numberLabel.layer.masksToBounds = true;
    cell.numberLabel.layer.cornerRadius = 15;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.numberLabel.text = [NSString stringWithFormat:@"%c", 'A'+indexPath.row];
    AnswerModel *model = [self getTheFitModel:tableView];
    
    //1为选择题2为判断题
    if([model.mtype intValue] == 1){
        cell.answerLabel.text = [[CommonUtils getAnswerWithString:model.mquestion] objectAtIndex:indexPath.row+1];
    }else{
        if(indexPath.row == 0){
            cell.answerLabel.text = @"对";
        }else{
            cell.answerLabel.text = @"错";
        }
    }
    int page = [self getQuestionNumber:tableView andCurPage:_currentPage];
    if([_hadAnswerArray[page] intValue] != 0){
        if([model.mtype intValue] == 1){
            if([model.manswer isEqualToString:[NSString stringWithFormat:@"%c", 'A'+indexPath.row]]){
                [self showNumberImage:cell.numberImage imageNamed:@"19"];
            }else if(![model.manswer isEqualToString:[NSString stringWithFormat:@"%c", 'A'+[_hadAnswerArray[page] intValue]-1]] && indexPath.row == [_hadAnswerArray[page] intValue]-1){
                [self showNumberImage:cell.numberImage imageNamed:@"20"];
            }else{
                cell.numberImage.hidden = true;
            }
        }else{
            if([model.manswer isEqualToString:cell.answerLabel.text]){
                [self showNumberImage:cell.numberImage imageNamed:@"19"];
            }else if(![model.manswer isEqualToString:cell.answerLabel.text] && indexPath.row == [_hadAnswerArray[page] intValue]-1){
                [self showNumberImage:cell.numberImage imageNamed:@"20"];
            }else{
                cell.numberImage.hidden = true;
            }
        }
    }else{
        cell.numberImage.hidden = true;
    }
    return cell;
}

- (void)showNumberImage:(UIImageView *)img imageNamed:(NSString *)name{
    img.hidden = false;
    img.image = [UIImage imageNamed:name];
}

- (AnswerModel *)getTheFitModel:(UITableView *)tableView{
    int index = [self getQuestionNumber:tableView andCurPage:_currentPage];
    return _datas[index];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGPoint currentOffset = scrollView.contentOffset;
    int page = currentOffset.x/SIZE.width;
    if(page < _datas.count-1 && page > 0){
        _scrollView.contentSize = CGSizeMake(currentOffset.x+SIZE.width*2, 0);
        _mainTableView.frame = CGRectMake(currentOffset.x, 0, SIZE.width, SIZE.height);
         _leftTableView.frame = CGRectMake(currentOffset.x-SIZE.width, 0, SIZE.width, SIZE.height);
        _rightTableView.frame = CGRectMake(currentOffset.x+SIZE.width, 0, SIZE.width, SIZE.height);
    }
    _currentPage = page;
    [_delegate scrollViewDidEndDecelerating];
    [self reloadData];
    DLog(@"page = %d", _currentPage);
}

- (void)reloadData{
    [_leftTableView reloadData];
    [_mainTableView reloadData];
    [_rightTableView reloadData];
}
@end
